package com.ropeok.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ropeok.Utils.JwtUtils;
import com.ropeok.Utils.RedisUtil;
import com.ropeok.dto.UserDto;
import com.ropeok.entity.permission;
import com.ropeok.service.serviceimpl.UserLoginServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private UserLoginServiceImpl userLoginService;


    @Autowired
    JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler){

        String requestURI = request.getRequestURI();
        //获取请求头中的令牌
        String token = request.getHeader("token");
        log.info("当前token为：{}", token);
        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            return  true;
        }
        //从请求中获取令牌
        DecodedJWT verify = JwtUtils.verify(token);
        String id = verify.getClaim("id").asString();
        System.out.println(id);
        return userLoginService.JudgePermission(id,requestURI);
//        Map<String, Object> map = new HashMap<>();
//        map.put("success",false);
//        map.put("code",401);
//        map.put("message","你没有权限");
//        String json = new ObjectMapper().writeValueAsString(map);
//        response.setContentType("application/json;charset=UTF-8");
//        response.getWriter().println(json);
    }
}
